<?php

namespace app\api\controller\develop;
use app\api\service\develop\DatagridCustomService;
use app\api\service\develop\TableFieldService;
use app\BaseController;
use app\api\service\develop\DatagridColumnService;
use app\util\CommonUtil;
use app\api\service\log\AdminOperateLogService;
use app\util\AdminUserUtil;
use app\util\ResponseUtil;

class DatagridColumn extends BaseController
{
    private $arrFieldTitle = array('is_in_add' => '新增是否包含', 'is_in_edit'=>'编辑是否包含', 'is_hide'=>'是否隐藏', 'is_require'=>'是否必需',
        'sort' => '排序', 'column_title' => '列名', 'column_width' => '列宽', 'status'=>'状态');

    public function getDatagridColumnInfo()
    {
        $id = $this->requestData['id'];
        $service = new DatagridColumnService();
        $finalData = $service->findRowById($id);
        return ResponseUtil::success($finalData);
    }

    public function getDatagridColumnList()
    {
        $pageIndex = $this->requestData['page'];
        $pageSize = $this->requestData['rows'];
        $service = new DatagridColumnService();
        $list = $service->getListWithPage($this->requestData, $pageIndex, $pageSize);
        $total = $service->getTotalNum($this->requestData);
        $finalData = CommonUtil::getPaginationData($list, $total);
        return ResponseUtil::success($finalData);
    }

    public function getDatagridColumnOption()
    {
        $service = new DatagridColumnService();
        $list = $service->getListNoPage($this->requestData);
        return ResponseUtil::success($list);
    }

    public function addDatagridColumn()
    {
        try{
            if(empty($this->requestData['datagrid_id'])){
                return ResponseUtil::failure("请指定数据表");
            }

            if(empty($this->requestData['column_name'])){
                return ResponseUtil::failure("列标识码不可为空");
            }

            if(empty($this->requestData['column_title'])){
                return ResponseUtil::failure("列名不可为空");
            }

            $service = new DatagridColumnService();
            $this->requestData['table_field_id'] = 0;
            $res = $service->createRow($this->requestData);
            if($res){
                $addInfo = CommonUtil::getDataInsertMessage($this->requestData, $this->arrFieldTitle);
                $message = '新增数据表纵列';
                if($addInfo){
                    $message .= ','.$addInfo;
                }
                $logData = [
                    'subject_id' => $res,
                    'remark'  => '',
                    'description' => $message,
                ];
                AdminUserUtil::addOperateLog('DatagridColumn', AdminOperateLogService::ARR_ACTION_TYPE['add'], $logData);
                return ResponseUtil::success($res);
            }else{
                return ResponseUtil::failure("新增数据表纵列失败");
            }
        }catch(\Exception $e){
            CommonUtil::addErrorLog(__CLASS__, __FUNCTION__,  CommonUtil::getExceptionMessage($e));
            return ResponseUtil::failure("新增数据表纵列失败");
        }
    }

    public function editDatagridColumn()
    {
        try{
            if(empty($this->requestData['id'])){
                return ResponseUtil::failure("请指定要编辑的页面纵列");
            }

            $id = $this->requestData['id'];
            $service = new DatagridColumnService();
            $oldInfo = $service->findRowById($id);
            if(empty($oldInfo)){
                return ResponseUtil::failure("数据不存在");
            }

            $res = $service->updateRowById($id, $this->requestData);
            if($res){
                $changeInfo = CommonUtil::getChangeData($oldInfo, $this->requestData, $this->arrFieldTitle);
                $message = '编辑页面纵列,'.$changeInfo['update_info'];
                $logData = [
                    'subject_id' => $id,
                    'remark'  => '',
                    'description' => $message,
                ];
                AdminUserUtil::addOperateLog('DatagridColumn', AdminOperateLogService::ARR_ACTION_TYPE['edit'], $logData);
                return ResponseUtil::success();
            }else{
                return ResponseUtil::failure("编辑页面纵列失败");
            }
        }catch(\Exception $e){
            CommonUtil::addErrorLog(__CLASS__, __FUNCTION__,  CommonUtil::getExceptionMessage($e));
            return ResponseUtil::failure("编辑页面纵列失败");
        }
    }

    public function deleteDatagridColumn()
    {
        try{
            $id = $this->requestData['id'];
            $service = new DatagridColumnService();
            $info = $service->findRowById($id);
            if(!$info){
                return ResponseUtil::failure("数据不存在");
            }

            $res = $service->removeRowById($id);
            if($res){
                $deleteInfo = CommonUtil::getDataDeleteMessage($info, $this->arrFieldTitle);
                $message = '删除页面纵列';
                if($deleteInfo){
                    $message .= ','.$deleteInfo;
                }
                $logData = [
                    'subject_id' => $id,
                    'remark'  => '',
                    'description' => $message,
                ];
                AdminUserUtil::addOperateLog('DatagridColumn', AdminOperateLogService::ARR_ACTION_TYPE['delete'], $logData);
                return ResponseUtil::success();
            }else{
                return ResponseUtil::failure("删除页面纵列失败");
            }
        }catch(\Exception $e){
            CommonUtil::addErrorLog(__CLASS__, __FUNCTION__,  CommonUtil::getExceptionMessage($e));
            return ResponseUtil::failure("删除页面纵列失败");
        }
    }

    public function deleteMultiDatagridColumn(){
        try{
            $arrId = $this->requestData['arr_id'];
            if(!is_array($arrId)){
                return ResponseUtil::failure("参数格式有误");
            }
            $service = new DatagridColumnService();
            $deleteData = [];
            foreach($arrId as $id){
                $info = $service->findRowById($id);
                if(!$info){
                    return ResponseUtil::failure("数据不存在");
                }
                $deleteData[] = $info;
            }
            $res = $service->removeListByManyId($arrId);
            if($res){
                $message = '删除页面纵列';
                $logData = [
                    'subject_id' => json_encode($arrId),
                    'remark'  => '',
                    'description' => $message,
                ];
                AdminUserUtil::addOperateLog('DatagridColumn', AdminOperateLogService::ARR_ACTION_TYPE['delete'], $logData);
                return ResponseUtil::success();
            }else{
                return ResponseUtil::failure("删除页面纵列失败");
            }
        }catch(\Exception $e){
            CommonUtil::addErrorLog(__CLASS__, __FUNCTION__,  CommonUtil::getExceptionMessage($e));
            return ResponseUtil::failure("删除页面纵列失败");
        }
    }

    public function toggleDatagridColumn()
    {
        try{
            if(empty($this->requestData['id'])){
                return ResponseUtil::failure("请指定要编辑的数据");
            }

            $arrField = ['is_in_add', 'is_in_edit', 'is_require', 'is_hide', 'status', 'is_fix'];
            $arrFieldTitle = [];
            if(empty($this->requestData['field_name'])){
                return ResponseUtil::failure("请指定要编辑的列");
            }

            $id = $this->requestData['id'];
            $fieldName = $this->requestData['field_name'];
            if(!in_array($fieldName, $arrField)){
                return ResponseUtil::failure("不支持编辑当前列");
            }

            $service = new DatagridColumnService();
            $oldInfo = $service->findRowById($id);

            $updateData[$fieldName] = empty($this->requestData['value']) ? 2:$this->requestData['value'];
            $res = $service->updateRowById($id, $updateData);
            if($res){
                $changeInfo = CommonUtil::getChangeData($oldInfo, $updateData, $this->arrFieldTitle);
                $message = '编辑页面纵列,'.$changeInfo['update_info'];
                $logData = [
                    'subject' => $id,
                    'remark'  => $oldInfo['column_name'],
                    'description' => $message,
                ];
                AdminUserUtil::addOperateLog('DatagridColumn', AdminOperateLogService::ARR_ACTION_TYPE['edit'], $logData);
                return ResponseUtil::success();
            }else{
                return ResponseUtil::failure("更新失败");
            }
        }catch(\Exception $e){
            CommonUtil::addErrorLog(__CLASS__, __FUNCTION__,  CommonUtil::getExceptionMessage($e));
            return ResponseUtil::failure("更新失败");
        }
    }

    public function simpleUpdateDatagridColumn()
    {
        try{
            if(empty($this->requestData['id'])){
                return ResponseUtil::failure("请指定要编辑的数据");
            }

            $id = $this->requestData['id'];
            $service = new DatagridColumnService();
            $oldInfo = $service->findRowById($id);
            if(empty($oldInfo)){
                return ResponseUtil::failure("数据不存在");
            }
            $res = $service->updateRowById($id, $this->requestData);
            if($res){
                $changeInfo = CommonUtil::getChangeData($oldInfo, $this->requestData, $this->arrFieldTitle);
                $message = '编辑页面纵列,'.$changeInfo['update_info'];
                $logData = [
                    'subject' => $id,
                    'remark'  => $oldInfo['column_name'],
                    'description' => $message,
                ];
                AdminUserUtil::addOperateLog('DatagridColumn', AdminOperateLogService::ARR_ACTION_TYPE['edit'], $logData);
                return ResponseUtil::success();
            }else{
                return ResponseUtil::failure("编辑失败");
            }
        }catch(\Exception $e){
            CommonUtil::addErrorLog(__CLASS__, __FUNCTION__,  CommonUtil::getExceptionMessage($e));
            return ResponseUtil::failure("编辑失败");
        }
    }

    /**
     * Desc:同步更新列名及排序
     * Datetime: 2024/11/9 16:13 by zdb
     */
    public function synUpdateDatagridColumn()
    {
        if(empty($this->requestData['arr_id'])){
            return ResponseUtil::failure("请指定要同步的数据");
        }

        $arrId = $this->requestData['arr_id'];
        if(!is_array($arrId)){
            return ResponseUtil::failure("参数格式有误");
        }

        $serviceDatagridColumn = new DatagridColumnService();
        $listDatagridColumn = $serviceDatagridColumn->getListByManyId($arrId);

        $arrFieldId = array_column($listDatagridColumn, 'table_field_id');
        $serviceTableField = new TableFieldService();
        $listTableField = $serviceTableField->getListByManyId($arrFieldId);
        $listTableFieldByFieldId = array_column($listTableField, null, 'id');

        $count = 0;
        //已经修改的类型，不可再被更新还原
        $arrModifiedElementType = array('select', 'radio', 'time', 'integer', 'switch');
        foreach($listDatagridColumn as $item){
            $fieldId = $item['table_field_id'];
            $fieldInfo = $listTableFieldByFieldId[$fieldId];
            $elementType = "text";
            if(in_array($fieldInfo['data_type'], ['date', 'datetime'])){
                $elementType = $fieldInfo['data_type'];
            }
            $updateData = array(
                'column_title' => $fieldInfo['field_title'],
                'sort' => $fieldInfo['sort'],
                'element_type' => $elementType
            );
            $condition = array('id' => $item['id'], 'element_type' => array('not in', $arrModifiedElementType));
            $res = $serviceDatagridColumn->updateListByData($condition, $updateData);
            if(false !== $res){
                $count++;
            }
        }
        if($count == count($arrId)){
            return ResponseUtil::success();
        }else{
            return ResponseUtil::failure("同步失败");
        }
    }

    /**
     * Desc: 同步新增
     * 出现在table field但datagrid column里没有的，则同步过来
     * Datetime: 2024/11/18 8:45 by zdb
     */
    public function synAddDatagridColumn()
    {
        try{
            if(empty($this->requestData['datagrid_id'])){
                return ResponseUtil::failure("请指定数据表");
            }
            $datagridId = $this->requestData['datagrid_id'];
            $datagridCustomService = new DatagridCustomService();
            $datagridInfo = $datagridCustomService->findRowById($datagridId);
            if(!$datagridInfo){
                return ResponseUtil::failure("数据表不存在");
            }

            $tableId = $datagridInfo['table_id'];
            $datagridColumnService = new DatagridColumnService();
            $datagridColumnList = $datagridColumnService->getListNoPage(array('datagrid_id' => $datagridId));
            $curFieldIdList = array_column($datagridColumnList, 'table_field_id');

            $serviceTableField = new TableFieldService();
            $originalFieldList = $serviceTableField->getListNoPage(array('table_id' => $tableId));
            $originalFieldIdList = array_column($originalFieldList, 'id');
            $originalFieldIdListById = array_column($originalFieldList, null,'id');

            $arrAddFieldId = array_diff($originalFieldIdList, $curFieldIdList);
            if(!$arrAddFieldId){
                return ResponseUtil::failure("已全部同步");
            }

            $addData = array();
            foreach($arrAddFieldId as $fieldId){
                $addData[] = array(
                    'datagrid_id' => $datagridId,
                    'table_field_id' => $fieldId,
                    'column_title' => $originalFieldIdListById[$fieldId]['field_title'],
                    'column_name' => $originalFieldIdListById[$fieldId]['field_name'],
                );
            }
            $res = $datagridColumnService->createManyRow($addData);
            if($res){
                return ResponseUtil::success([], "同步成功");
            }else{
                return ResponseUtil::failure("同步失败");
            }
        }catch(\Exception $e){
            CommonUtil::addErrorLog(__CLASS__, __FUNCTION__,  CommonUtil::getExceptionMessage($e));
            return ResponseUtil::failure("同步失败");
        }
    }

    /**
     * 绑定数据字典
     * @return \think\response\Json
     */
    public function bindDictionary()
    {
        try{
            if(empty($this->requestData['id'])){
                return ResponseUtil::failure("请指定列数据");
            }

            $id = $this->requestData['id'];
            $datagridColumnService = new DatagridColumnService();
            $datagridColumnInfo = $datagridColumnService->findRowById($id);
            if("select" != $datagridColumnInfo['element_type']){
                return ResponseUtil::failure("只有select类型才可以绑定数据字典");
            }

            $updateData = array(
                'dictionary_id' => $this->requestData['dictionary_id']
            );
            $res = $datagridColumnService->updateRowById($id, $updateData);
            if($res){
                return ResponseUtil::success([], "绑定成功");
            }else{
                return ResponseUtil::failure("绑定失败");
            }
        }catch(\Exception $e){
            CommonUtil::addErrorLog(__CLASS__, __FUNCTION__,  CommonUtil::getExceptionMessage($e));
            return ResponseUtil::failure("绑定失败");
        }
    }

}



